package com.zhenghaijin.searchservice.service.impl;

import com.zhenghaijin.searchservice.mapper.AnimeMapper;
import com.zhenghaijin.searchservice.model.Anime;
import com.zhenghaijin.searchservice.model.PageResult;
import com.zhenghaijin.searchservice.service.AnimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AnimeServiceImpl implements AnimeService {

    @Autowired
    private AnimeMapper animeMapper;

    @Override
    public PageResult<Anime> search(String keyword, String category, String tag, int page, int size) {
        // 计算偏移量
        int offset = (page - 1) * size;
        // 查询数据列表
        List<Anime> list = animeMapper.search(keyword, category, tag, offset, size);
        // 查询总记录数
        Long total = animeMapper.countByConditions(keyword, category, tag);
        // 封装分页结果
        return new PageResult<>(total, list, page, size);
    }

    @Override
    public void syncAnimeData(List<Anime> animeList) {
        // 清空本地 anime 表
        animeMapper.deleteAll();
        // 批量插入数据
        if (animeList != null && !animeList.isEmpty()) {
            for (Anime anime : animeList) {
                animeMapper.insertAnime(anime);
            }
        }
    }
}